<?php
namespace control;

/*
*社会保险类
*/

class workInsureClass extends adIndexClass
{
    private const table = 'staff_insure';
    private const page = 'workInsure';
    private const title = '社会保险';

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow = '待参保'): string
    {
        $html = '';
        //生成查询表单
        if ($workFlow =='待参保'){
            $html .=
                text(array('name' => 'name', 'title' => '姓名')) .
                selectMultiple(array("name" => "departmentId", "title" => "部门", "table" => "department", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id')) .
                selectMultiple(array("name" => "jobId", "title" => "职位", "table" => "job", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id')) .
                text(array('name' => 'idCard', 'title' => '身份证号')) .
                text(array('name' => 'tel', 'title' => '手机号')) .
                text(array("name" => "startTime", 'laydate' => ['range' => '~'], 'class' => 'width200', "title" => "入职日期-入职日期"));
        }elseif($workFlow =='参保中'){
            $html .=
                text(array('name' => 'name', 'title' => '姓名')) .
                selectMultiple(array("name" => "departmentId", "title" => "部门", "table" => "department", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id')) .
                selectMultiple(array("name" => "jobId", "title" => "职位", "table" => "job", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id')) .
                text(array('name' => 'idCard', 'title' => '身份证号')) .
                text(array('name' => 'tel', 'title' => '手机号')) .
                text(array('name' => 'insureNo', 'title' => '社保号')) .
                text(array("name" => "startTime", 'laydate' => ['range' => '~'], 'class' => 'width200', "title" => "参保日期-参保日期"));
        }elseif($workFlow =='待停保'){
            $html .=
                text(array('name' => 'name', 'title' => '姓名')) .
                selectMultiple(array("name" => "departmentId", "title" => "部门", "table" => "department", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id')) .
                selectMultiple(array("name" => "jobId", "title" => "职位", "table" => "job", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id')) .
                text(array('name' => 'idCard', 'title' => '身份证号')) .
                text(array('name' => 'tel', 'title' => '手机号')) .
                text(array('name' => 'insureNo', 'title' => '社保号')) .
                text(array("name" => "startTime", 'laydate' => ['range' => '~'], 'class' => 'width200', "title" => "参保日期-参保日期")).
                text(array("name" => "quitTime", 'laydate' => ['range' => '~'], 'class' => 'width200', "title" => "离职日期-离职日期"));
        }elseif($workFlow =='已停保'){
            $html .=
                text(array('name' => 'name', 'title' => '姓名')) .
                selectMultiple(array("name" => "departmentId", "title" => "部门", "table" => "department", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id')) .
                selectMultiple(array("name" => "jobId", "title" => "职位", "table" => "job", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id')) .
                text(array('name' => 'idCard', 'title' => '身份证号')) .
                text(array('name' => 'tel', 'title' => '手机号')) .
                text(array('name' => 'insureNo', 'title' => '社保号')) .
                text(array("name" => "startTime", 'laydate' => ['range' => '~'], 'class' => 'width200', "title" => "参保日期-参保日期")).
                text(array("name" => "quitTime", 'laydate' => ['range' => '~'], 'class' => 'width200', "title" => "停保日期-停保日期"));
        }

        return $this->search($html, 'menu');
    }

    /*行政人事-出差记录-查询条件*/
    public function home($workFlow = '待参保')
    {
        $data = [
            "id" => "all",
            "menu" => [
                "draft" => "待参保",
                "signing" => "参保中",
                "effecting" => "待停保",
                "ending" => "已停保",
            ]
        ];
        $data['html'] = $this->homeForm($workFlow);
        return $this->tab($data);
    }

    /*行政人事-出差记录-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            "b.jobId" => $this->post('jobId'),
            "a.workFlow" => '待参保'
        );
        //like查询数组
        $like = array(
            "b.name" => $this->post('name'),
            "c.idCard" => $this->post('idCard'),
            "b.tel" => $this->post('tel'),
        );

        //初始化
        $and = "";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 're.entryDate');
        }
        if ($this->post('departmentId')) {
            $and .= " and b.jobId in (select id from job where departmentId = '" . $this->post('departmentId') . "')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join staff as b on b.stid = a.staffId join talent_pool as c on c.id = a.talentId join staff_entry_record as re on (re.talentId = a.talentId and re.id not in (select entryId from staff_quit_record where isConfirm = 1)) ",
            'field' => "a.*,b.name,c.idCard,b.tel,b.state as jobState,re.entryDate,b.jobId",
            "where" => $where,
            "order" => "re.entryDate desc,a.orderNo desc"));
        //获取表头
        $tr[] = array('', '姓名', "部门", '职位', "身份证号", "手机号", "入职日期", "入职天数", "在职状态");
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        $obj = new workContractClass();
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "edit" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $job = query('job', "id = '$array[jobId]'");
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['name'], departmentClass::getTypeName($job['departmentId']), $job['name'], $array['idCard'], $array['tel'], $array['entryDate'], $obj->countDay($array['entryDate'], $this->date), $array['jobState']);
        }
        //控件
        $button = "";

        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        $talent = query('talent_pool', "id = '$info[talentId]'");
        $staff = query('staff', "stid = '$info[staffId]'");
        $staffEntry = query('staff_entry_record', "talentId = '$info[talentId]' order by time desc");
        $staffFormal = query('staff_formal', "staffId = '$info[staffId]' order by time desc");
        //按钮
        $button[] = [
	        "name"  => L('public.submit'),
            "type" => "点击事件",
            "cla" => $this->get('cla'),
            "fun" => "subForm('" . self::page . "EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
            "post" => ["id" => $this->get('id')],
            'style' => 'li-btn-blue-bg',
        ];
	    $button[]  = [
		    "name"  => L('public.saveDraft'),
		    "type"  => "点击事件",
		    "cla"   => $this->get('cla'),
		    "fun"   => "saveTemp('" . self::page . "', 'edit', '" . self::page . "EditForm')",
		    "post"  => ["id" => $this->get('id')],
		    'style' => 'li-btn-green-bg',
	    ];
        $job = query('job', "id = '$staff[jobId]'");
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button)
                ],
                [
                    "<span class='small-title'>员工基本信息</span>"
                ],
                [
                    "姓名：" => $talent['name'],
                    "身份证号：" => $talent['idCard'],
                    '手机号：' => $talent['tel'],
                ],
                [
                    "部门：" => departmentClass::getTypeName($job['departmentId']),
                    "职位：" => $job['name'],
                    '入职日期：' => $staffEntry['entryDate']
                ],
                [
                    '转正日期：' => self::null($staffFormal['confirmDate']),
                    '在职状态：' => $staff['state'],
                    '社会保险：' => $staffEntry['insure'],
                ],
                [
                    "<span class='small-title'>参保信息</span>"
                ],
                [
                    must . "参保日期：" => text(["name" => "insureDate", 'laydate' => [], "value" => $info['insureDate'] ?: $this->date]),
                    must . "社保号：" => text(["name" => "insureNo", "value" => $info['insureNo']]),
                ],
                [
                    must . "保险种类：" => checkbox(["name" => "type", 'value' => explode('，', para('insureOption')), "checked" => $info['type'] ? explode(',', $info['type']) : explode('，', para('insureOption'))]),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
                [
                    "<div><span class='small-title'>附件</span></div>"
                ],
                [
                    fileUploadClass::addFileComponent($info['id'], '社会保险', self::page, self::page . 'EditForm'),
                ]
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $this->get('id'))),
            'button' => ' '
        ]);
        //返回
        return $this->tab($data);
    }

    public function signing(): bool|string
    {
        $json['html'] = $this->homeForm('参保中');
        return json_encode($json, 320);
    }

    public function signingSearch(): bool|string
    {
        //全等查询数组
        $equal = array(
            "b.jobId" => $this->post('jobId'),
        );
        //like查询数组
        $like = array(
            "b.name" => $this->post('name'),
            "c.idCard" => $this->post('idCard'),
            "b.tel" => $this->post('tel'),
            "a.insureNo" => $this->post('insureNo'),
        );

        //初始化
        $and = " and a.workFlow in ('参保中','待停保')";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'a.insureDate');
        }
        if ($this->post('departmentId')) {
            $and .= " and b.jobId in (select id from job where departmentId = '" . $this->post('departmentId') . "')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join staff as b on b.stid = a.staffId join talent_pool as c on c.id = a.talentId join staff_entry_record as re on (re.talentId = a.talentId and re.id not in (select entryId from staff_quit_record where isConfirm = 1)) ",
            'field' => "a.*,b.name,c.idCard,b.tel,b.state as jobState,re.entryDate,b.jobId",
            "where" => $where,
            "order" => "re.entryDate desc,a.orderNo desc"));
        //获取表头
        $tr[] = array('', '姓名', "部门", '职位', "身份证号", "手机号", "入职日期", "参保日期",'社保号', "在职状态");
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "edit" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $job = query('job', "id = '$array[jobId]'");
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['name'], departmentClass::getTypeName($job['departmentId']), $job['name'], $array['idCard'], $array['tel'], $array['entryDate'],$array['insureDate'],$array['insureNo'], $array['jobState']);
        }
        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='signingForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    public function effecting()
    {
        $json['html'] = $this->homeForm('待停保');
        return json_encode($json, 320);
    }

    public function effectingSearch()
    {
        //全等查询数组
        $equal = array(
            "b.jobId" => $this->post('jobId'),
            "a.workFlow" => '待停保'
        );
        //like查询数组
        $like = array(
            "b.name" => $this->post('name'),
            "c.idCard" => $this->post('idCard'),
            "b.tel" => $this->post('tel'),
            "a.insureNo" => $this->post('insureNo'),
        );

        //初始化
        $and = "";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'a.insureDate');
        }
        if ($this->post('departmentId')) {
            $and .= " and b.jobId in (select id from job where departmentId = '" . $this->post('departmentId') . "')";
        }
        $whereQit = '';
        if ($this->post('quitTime')) {
            $whereQit .= self::timeComparison($this->post('quitTime'), field: 'confirmDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join staff as b on b.stid = a.staffId join talent_pool as c on c.id = a.talentId join staff_entry_record as re on (re.talentId = a.talentId and re.id = (select entryId from staff_quit_record where isConfirm = 1 and staffId = a.staffId $whereQit order by time desc limit 1)) ",
            'field' => "a.*,b.name,c.idCard,b.tel,b.state as jobState,re.entryDate,b.jobId,re.id as eid",
            "where" => $where,
            "order" => "re.entryDate desc,a.orderNo desc"));
        //获取表头
        $tr[] = array('', '姓名', "部门", '职位', "身份证号", "手机号", "入职日期", "参保日期",'社保号','离职日期', "在职状态");
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "edit" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $job = query('job', "id = '$array[jobId]'");
            $staff_quit_record = query('staff_quit_record',"entryId = '$array[eid]'");
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['name'], departmentClass::getTypeName($job['departmentId']), $job['name'], $array['idCard'], $array['tel'], $array['entryDate'],$array['insureDate'],$array['insureNo'],$staff_quit_record['confirmDate'], $array['jobState']);
        }
        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='effectingForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function ending(): bool|string
    {
        $json['html'] = $this->homeForm('已停保');
        return json_encode($json, 320);
    }

    public function endingSearch(): bool|string
    {
        //全等查询数组
        $equal = array(
            "b.jobId" => $this->post('jobId'),
            "a.workFlow" => '已停保'
        );
        //like查询数组
        $like = array(
            "b.name" => $this->post('name'),
            "c.idCard" => $this->post('idCard'),
            "b.tel" => $this->post('tel'),
            "a.insureNo" => $this->post('insureNo'),
        );

        //初始化
        $and = "";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'a.insureDate');
        }
        if ($this->post('quitTime')) {
            $and .= self::timeComparison($this->post('quitTime'), field: 'a.endDate');
        }
        if ($this->post('departmentId')) {
            $and .= " and b.jobId in (select id from job where departmentId = '" . $this->post('departmentId') . "')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join staff as b on b.stid = a.staffId join talent_pool as c on c.id = a.talentId join (select * from staff_entry_record  order by time desc) as re on re.talentId = a.talentId",
            'field' => "a.*,b.name,c.idCard,b.tel,b.state as jobState,re.entryDate,b.jobId,re.id as eid",
            "where" => $where,
            "order" => "re.entryDate desc,a.orderNo desc"));
        //获取表头
        $tr[] = array('', '姓名', "部门", '职位', "身份证号", "手机号", "入职日期", "参保日期",'社保号','离职日期','停保日期', "在职状态");
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "edit" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $job = query('job', "id = '$array[jobId]'");
            $staff_quit_record = query('staff_quit_record',"entryId = '$array[eid]'");
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['name'], departmentClass::getTypeName($job['departmentId']), $job['name'], $array['idCard'], $array['tel'], $array['entryDate'],$array['insureDate'],$array['insureNo'],$staff_quit_record['confirmDate'],$array['endDate'], $array['jobState']);
        }
        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='liftForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }



    /*编辑*/
    public function editEdit()
    {
        $id = $this->post('id');
        $field = [
            'insureDate' => $this->post('insureDate'),
            'insureNo' => $this->post('insureNo'),
            'type' => $this->post('type') ? implode(',', $this->post('type')) : '',
            'text' => $this->post('text'),
        ];
        $annotation = [
            'insureDate' => '参保日期',
            'insureNo' => '社保号',
            'type' => '保险种类',
            'text' => '备注',
        ];
        $rules = [
            'insureDate' => 'required|date',
            'insureNo' => 'required|unsigned_int',
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $entryResult = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($entryResult === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "您还没有编辑权限";
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此参保信息';
        } else {
            $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                //附件
                $fileIdArr = $this->post('fileId');
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                $obj = new workContractClass();
                $obj->judgeIsDiff($info, $field, $annotation);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
                $this->logText(array("type" => self::page, "text" => $text));
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }

        $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
        resp:
        return json_encode($json, 320);
    }


    /*出差详情*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = '未找到此' . self::title;
        } else {
            $info = query(self::table, " id = '" . $this->get('id') . "' ");
            if (empty($info['id'])) {
                $html = "未找到此记录";
            } else {
                //菜单
                $data = array(
                    "id" => $info['id'],
                    'menu'=>[
                        'detail'=>'基本信息',
                        'payRecord'=>'缴费记录'
                    ]
                );

                $button = [];
                if ($info['workFlow'] == '待参保') {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
                if ($this->power(self::page, "edit") && in_array($info['workFlow'], ['参保中', '待停保'])) {
                    $button[] = [
                        "name" => "停保",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "stopInsure",
                        "post" => ["id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
                if ($this->power(self::page, "edit") && $info['workFlow'] != '已停保') {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    ];
                }
                $tr[] = ['变更日期', '变更人', '变更内容'];
                $all = find(array('table' => 'staff_contract_change', 'where' => "contractId = '$info[id]' order by time desc"));
                foreach ($all['array'] as $array) {
                    $tr[] = [$array['time'], $array['name'], $array['text']];
                }

                $staff = query('staff', "stid = '$info[staffId]'");
                $talent = query('talent_pool', "id = '$info[talentId]'");
                $job = query('job', "id = '$staff[jobId]'");
                $staffEntry = query('staff_entry_record', "talentId = '$talent[id]' order by time desc");
                $staffFormal = query('staff_formal', "staffId = '$info[staffId]' order by time desc");
                //生成表单
                $data['html'] = $this->tableShow(array(
                    "button" => $button,
                    '员工基本信息' => array(
                        array(
                            "姓名" => $talent['name'],
                            "身份证号" => $talent['idCard'],
                            "手机号" => $talent['tel'],
                        ),
                        array(
                            "部门" => departmentClass::getTypeName($job['departmentId']),
                            "职位" => $job['name'],
                            "入职日期" => $staffEntry['entryDate'],
                        ),
                        array(
                            "转正日期" => $staffFormal['confirmDate'],
                            "在职状态" => $staff['state'],
                            "社会保险" => $staffEntry['insure']
                        ),
                    ),
                    '参保信息' => array(
                        array(
                            "社保号" => $info['insureNo'],
                            "保险种类" => $info['type'],
                        ),
                        array(
                            "备注" => $info['text'],
                        ),
                        array(
                            "参保日期" => $info['insureDate'],
                            "停保日期" => $info['endDate'],
                            "停保备注" => $info['endText'],
                        ),
                        array(
                            "备注" => $info['text'],
                        ),
                    ),
                    '附件' => array(
                        array(
                            fileUploadClass::showFile($info['id'])
                        ),
                    ),
                    '变更记录' => array(
                        array(
                            $this->tableMany(['tr' => $tr])
                        )
                    ),
                    '系统信息' => array(
                        array(
                            '编号' => $info['orderNo'],
                            '状态' => $info['workFlow'],
                        ),
                        array(
                            '创建人' => self::findStaff($info['stid']),
                            '创建时间' => $info['time'],
                            '更新时间' => $info['updateTime'],
                        )
                    )
                ));
                //生成页面
                $html = $this->tab($data);
            }
        }
        //返回
        return $html;
    }

    /**
     * 停保
     */
    public function stopInsure(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    must."停保日期：" => text(array('name'=>'endDate','laydate'=>[],'value'=>$this->date)),
                ),
                array(
                    "停保备注："=>textarea(array('name'=>'endText','class'=>'textarea'))
                )
            ),
        ));
        //返回
        return $this->layer(array("title" => "停保", "height" => 300, "width" => 800, "html" => $html));
    }

    /**
     * 停保
     */
    public function stopInsureEdit(): bool|string
    {
        $id = $this->post('id');
        $field = [
            'endDate' => $this->post('endDate'),
            'endText' => $this->post('endText'),
            'workFlow'=>'已停保'
        ];
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($id)) {
            $json['warn'] = "未找到ID";
        } else {
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id = '$id'"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $obj = new workContractClass();
                $obj->insertRecord(array(
                    'text' => $this->control['name'] . "停保了参保信息",
                    'contractId' => $id
                ));
                //添加日志
                $text = $this->control['name'] ."停保了" . self::title . "， id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '停保成功';
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'workFlow' => '参保中',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此社会保险';
        } elseif ($info['workFlow'] != '待参保') {
            $json['warn'] = '此记录不是待参保状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $obj = new workContractClass();
                $obj->insertRecord(array(
                    'text' => $this->control['name'] . "提交了参保信息",
                    'contractId' => $info['id']
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此' . self::title . '，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '提交后此参保信息将变为参保中，是否确认提交此' . self::title . '？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 缴费记录
     */
    public function payRecord()
    {
        $html =
            repeatSelect(array("name" => "subject", "title" => "费款科目", 'sqlForm' => 'insure', 'sqlField' => 'subject')) .
            text(array("name" => "payMoon", 'laydate' => ['type' => 'month', 'range' => '~'], "title" => "缴款月份")) .
            text(array("name" => "moon", 'laydate' => ['type' => 'month', 'range' => '~'], "title" => "所属月份")) .
            select(array("name" => "orderBy", "title" => "排序", "option" => array("缴款月份", "所属月份"))) .
            hidden(array('name' => 'id', 'value' => $this->get('id')));
        $json['html'] = $this->search($html);
        return json_encode($json, 320);
    }

    /**
     * 缴费记录
     * @return bool|string
     */
    public function payRecordSearch()
    {
        $id = $this->post('id');
        $and = " and stid = '$id'";
        $like = [
        ];
        $equal = [
            "subject" => $this->post('subject'),//费款科目
        ];
        if ($this->post('payMoon')) {
            $timeArr = explode(' ~ ', $this->post('payMoon'));
            $and .= " and payMoon >='{$timeArr[0]}' and payMoon <='{$timeArr[1]}'";
        }
        if ($this->post('moon')) {
            $timeArr = explode(' ~ ', $this->post('moon'));
            $and .= " and moon >='{$timeArr[0]}' and moon <='{$timeArr[1]}'";
        }

        $where = search(["like" => $like, "=" => $equal]) . $and;
        //排序
        $orderBy = $this->orderBy(array(
            "search" => $this->post('orderBy')??null,
            "default" => "缴款月份",
            "array" => array(
                "payMoon" => array("desc" => "缴款月份", "site" => 3),
                "moon" => array("desc" => "所属月份", "site" => 4),
            ),
        ));
        $page = $this->page([
            "table" => "insure",
            "where" => $where,
            "order" => $orderBy['orderBy'],
        ]);
        //获取表头
        $tr[] = ["员工", "费款科目", "缴款月份", "所属月份", "缴费基数(".static::$unit.")", "个人缴纳(".static::$unit.")", "单位缴帐户(".static::$unit.")", "单位缴统筹(".static::$unit.")", "缴费类别"];
        //获取记录
        foreach ($page['array'] as $array) {
            //数据库查询
            $staff = query("staff", " stid = '$array[stid]' ");
            $tr[] = array(
                $staff['name'], $array['subject'], $array['payMoon'], $array['moon'], $array['base'], $array['personal'], $array['company'], $array['fund'], $array['type']
            );
        }
        //控件
        $button = "";
        $json['html'] = $page['hint'] . $button . "<form name='topicForm'>" . space . $this->tableMany(array("tr" => $tr, "orderBySign" => $orderBy)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }
}